// pages/cart/component/cart.js
import {ComponentWithStore} from 'mobx-miniprogram-bindings'
const computebehavior= require("miniprogram-computed").behavior
import {userstore} from "@/store/userstore"
import {reqcartlist,updatacart,removecart} from '@/api/cart'
import {debounce} from 'miniprogram-licia'
ComponentWithStore({
  behaviors:[computebehavior],
  properties: {},
  data: {
    cartList:[],
    emptyDes: '还没有添加商品，快去添加吧～'
  },
  methods: {
    async updatachecked(e){
      await updatacart({
        goodid:e.currentTarget.dataset.id,
        ischeck:e.detail
      })
      this.getcartlist()
    },
    async getcartlist(){
      const res=await reqcartlist()
      this.setData({
        cartList:res.data
      })
    },
    onShow(){
      this.getcartlist()
    },
    async changeallcheck(e){
      this.setData({
        allchecked:e.detail
      })
      await updatacart({
        isallcheck:e.detail
      })
      this.getcartlist()
    },
    async removecart(e){
      const {id}=e.currentTarget.dataset
      await removecart(id)
      this.getcartlist()
    },
    changecount:debounce(async function(e){
      const {id}=e.currentTarget.dataset
      await updatacart({
        goodid:id,
        count:e.detail
      })
    },500),
    topay(){
      wx.navigateTo({
        url: "/modules/orderpaymodule/pages/order/detail/detail",
      })
    }
  },
  storeBindings:{
    store:userstore,
    fields:["token"]
  },
  computed:{
    allchecked(data){
      let flag=true
      data.cartList.forEach(e => {
        if(e.ischeck==false){
          flag=false
          return false
        }
      });
      return flag
    },
    total(data){
      let total=0
      data.cartList.forEach(e => {
        if(e.ischeck==true){
          total+=e.price*e.count
        }
      });
      return total
    }
  }
})
